# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(scatterplot3d)
library(optparse)
library(tidyverse)
library(magrittr)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "", type = "character", help = "sample color file"),
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))

if (!file.exists(opt$sc)) {
  file.copy("Class_Color.txt", opt$sc)
}

sampleInfo <- read_tsv(opt$g,col_types = "cc") %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

parent <- "./"
createWhenNoExist(parent)

sampleColDf <- tibble(ClassNote = plotConfigJson$color$groups, col = plotConfigJson$color$colors)

pcDataFileName <- paste0(parent, "/PCA_Score.csv")

xPc <- x %>%
  str_c("PC", .)
yPc <- y %>%
  str_c("PC", .)
zPc <- z %>%
  str_c("PC", .)

zPc

pc123 <- read_csv(pcDataFileName) %>%
  rename(SampleID = X1) %>%
  select(c("SampleID", xPc, yPc, zPc)) %>%
  set_colnames(c("SampleID", "xPc", "yPc", "zPc")) %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  left_join(sampleColDf, by = c("ClassNote"))

parameterFileName <- paste0(parent, "/PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")

impoPc1 <- parameterData[1, xPc]
impoPc1 <- round(impoPc1 * 100, 2)
impoPc2 <- parameterData[1, yPc]
impoPc2 <- round(impoPc2 * 100, 2)
impoPc3 <- parameterData[1, zPc]
impoPc3 <- round(impoPc3 * 100, 2)

fileName <- paste0(parent, "/PCA_Score_3D.pdf")

pdf(fileName, width = width, height = height)

opar <- par(no.readonly = TRUE)
par(family = fontFamily)

main <- if (!is.na(mainTitle)) {
  mainTitle
} else ""

scatterplot3d(pc123$xPc, pc123$yPc, pc123$zPc, color = pc123$col, main = main, pch = 20, col.axis = "grey",
              mar = c(5, 3, 1, 3) + 0.1, cex.symbols = 6, xlab = str_c(xPc, "(", impoPc1, "%)"), ylab = str_c(yPc, "(", impoPc2, "%)"),
              zlab = str_c(zPc, "(", impoPc3, "%)"), angle = 60, cex.lab = 2, cex.axis = 1.5)

par(opar)

dev.off()
